<template>
  <div class="home-list">
    <Tabs type="card" v-model="currentTab" closable :animated="false" @on-tab-remove="removeTab" @on-click="toHomeDetail">
      <TabPane label="房态列表" :closable='false' name='/'>
        <div style="display: flex;">

          <Card dis-hover style="flex:1" class="no-border-card">
            <p slot="title" style="color:#495060">设备</p>
            <Affix class="ivu-affix sidebar-ani" style="top: 126px;"
              :style="{ 'right': sidebarVisible ? '22px' : '-370px' }"
              :offset-top="0">
              <Sidebar
                :home="selectedHome"
                :room="selectedRoom"
                @on-open-room="openRoom"
                @on-update="refreshHomeList"
                @on-close="hideSidebar"
              />
            </Affix>
            <homeSearchBar
              @on-search="search"
              @on-filter-home-type="filterHomeType"
              @on-filter-store="filterStore"
            />

            <div class="color-wrap">
              <span class="color1"></span>无设备
              <span class="color2"></span>设备正常
              <span class="color3"></span>设备异常
            </div>

            <div v-show="!homes || !homes.length" class="no-data">
              暂无匹配的数据
            </div>
            <div style="position:relative">
              <Spin size="large" fix v-show="spinShow"></Spin>
              <div class="c-home-list" v-for="home in homes" :key="home.id">
                <div class="c-home-list__title">
                    <span class="c-home-list__title__main">{{home.homeType}}</span>
                    <div class="c-home-list__title__content">
                      <span>地址：{{home.homeLocation}}</span>
                      <span class="c-home-list__title__split">/</span>
                      <span class="no-break">小区：{{home.block}}</span>
                      <span class="c-home-list__title__split">/</span>
                      <span class="no-break">门店：{{(home.branch && home.branch.name) || '总部'}}</span>
                      <span class="c-home-list__title__split">/</span>
                      <span class="no-break">房源编号：{{home.home_name}}</span>
                    </div>
                    <i-button class="c-home-list__title__btn" type="ghost" @click="openHomeDetail(home)">
                      房源详情
                    </i-button>
                </div>
                <div class="c-home-rooms" v-if="home.home_type === 1">
                  <!-- 公区展示 -->
                  <div :class="{
                    'c-home-rooms__public': true,
                    'is-working': home.publicRoom.has_device && home.publicRoom.is_normal,
                    'is-error': home.publicRoom.has_device && !home.publicRoom.is_normal
                  }" @click="showSidebar(home, home.publicRoom)">
                    <div style="margin:auto">公区</div>
                    <Icon
                      class="c-home-rooms__tenant"
                      type="person"
                      v-if="home.publicRoom.has_tenant">
                    </Icon>
                  </div>
                  <!-- 分散式房源展示 -->
                  <div class="c-home-rooms__main">
                    <div class="c-home-rooms__list c-home-rooms__list--split">
                      <div
                        class="c-home-rooms__item__wrap"
                        v-for="(room, roomIndex) in home.rooms"
                        v-show="roomIndex < (home.shouldShowHideBtn ? 15 : 16)"
                        :key="room.id">
                        <div :class="{
                          'c-home-rooms__item': true,
                          'is-working': room.has_device && room.is_normal,
                          'is-error': room.has_device && !room.is_normal
                        }" @click="showSidebar(home, room)">
                          <div class="c-home-rooms__item__name">
                            {{room.room_name}}
                          </div>
                          <Icon
                            class="c-home-rooms__tenant"
                            type="person"
                            v-if="room.has_tenant">
                          </Icon>
                        </div>
                      </div>
                      <div class="c-home-rooms__item__wrap" v-show="home.shouldShowHideBtn">
                        <div class="c-home-rooms__item" @click="openHomeDetail(home)">
                          <div class="c-home-rooms__item__name">
                            更多
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                </div>
              </div>
            </div>

            <Page v-if="total" :current.sync="currPage" :total="total" :page-size="limit" show-elevator show-total style="text-align:center" @on-change="onPageChange"></Page>
          </Card>

          <div class="sidebar-ani2" :style="{ 'min-width': sidebarVisible ? '360px' : 0 }"></div>

        </div>


      </TabPane>

      <TabPane :label="homeItem.home_name" :name="'/' + homeItem.id" v-for="homeItem in openedTab" :key="homeItem.id" >
        <keep-alive>
          <router-view :home="homeItem" :room="openedRoom" :stores="homeItem.branch" @on-update="refreshHomeList" v-if="currentTab === '/' + homeItem.id"></router-view>
        </keep-alive>
      </TabPane>
    </Tabs>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
import debounce from 'lodash/debounce'
import { HomeTypeEnum, RoomTypeEnum } from '@/libs/const'
import { http, api } from '@/libs/http'
// import dataCenter from '@/libs/dataCenter';
import util from '@/libs/util'
import homeSearchBar from './homeSearchBar.vue'
import Sidebar from './sidebar.vue'
import { mapGetters } from 'vuex'

const LIMIT = 8

export default {
  name: 'home-list',
  components: {
    homeSearchBar,
    Sidebar
    // homeDetail
  },
  data () {
    return {
      params: {
        province: null,
        city: null,
        district: null,
        branch_id: null,
        home_type: null,
        keyword: null,
        offset: 0,
        limit: LIMIT
      },
      homesMap: null,
      HomeTypeEnum: HomeTypeEnum,
      RoomTypeEnum: RoomTypeEnum,

      span: 24,
      stores: null,
      spinShow: false,

      limit: LIMIT,
      currPage: 1,
      total: 0,
      homes: null,
      selectedHome: null,
      selectedRoom: null,
      openedRoom: null,

      sidebarVisible: false,
      highlightRoomId: '' // 房间是否高亮显示
    }
  },

  mounted () {
    this.params = {
      province: null,
      city: null,
      district: null,
      branch_id: null,
      home_type: null,
      keyword: null,
      offset: 0,
      limit: LIMIT
    }
    if (this.$route.query.input) {
      this.params.keyword = this.$route.query.input
    }
    this.loadData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize)
  },
  created () {
    if (this.$route.query.input) {
      this.params.keyword = this.$route.query.input
    }
    if (this.$route.params.homeId) {
      this.$store.dispatch('setCurrentTab', '/' + this.$route.params.homeId)
    }
  },
  watch: {
    $route (n) {
      if (n) {
        this.$store.dispatch('setCurrentTab', '/' + (this.$route.params.homeId || ''))
      }
    }
  },
  computed: {
    ...mapGetters(['openedTab']),
    currentTab: {
      get () {
        return this.$store.state.home.currentTab
      },
      set (val) {
        this.$store.dispatch('setCurrentTab', val)
      }
    }
  },
  methods: {
    handleResize: debounce(function () {
      this.homes = cloneDeep(this.homes)
    }, 200),
    async loadData () {
      try {
        this.spinShow = true
        this.selectedHome = null
        this.hideSidebar()
        this.params.keyword = this.params.keyword || null
        const homeRes = await http.req(api.home_list, null, this.params)
        if (!homeRes) return

        // 路由里面的房源id获取房源详情
        const homeId = this.$route.params.homeId
        if (homeId) {
          const homeFromRouter = await http.req(api.home_info, [homeId], null)
          if (homeFromRouter) this.$store.dispatch('addTab', homeFromRouter)
        }
        this.total = homeRes.count
        // homeRes.homes.sort((a, b) => a.home_type - b.home_type)
        const [ homeIds, homeMap, homeDetailIds ] = homeRes.homes.reduce(([ homeIds, homeMap, homeDetailIds ], home) => {
          if (home.home_type === 1) homeDetailIds.push(home.id)
          homeIds.push(home.id)
          homeMap[home.id] = {
            ...home,
            homeType: home.home_type === HomeTypeEnum.DECENTRALIZED ? '分散式' : '集中式',
            homeLocation: util.concatLocation(home),
            buildingIndex: 0,
            publicRoom: {},
            rooms: [],
            buildings: []
          }
          return [ homeIds, homeMap, homeDetailIds ]
        }, [ [], {}, [] ])
        const roomMap = await http.req(api.room_list_mul_homes, null, { limit: 17, home_ids: JSON.stringify(homeDetailIds) })
        Object.values(homeMap).forEach(home => {
          const rooms = roomMap[home.id]
          if (!rooms) return
          home.publicRoom = rooms.find(r => r.room_type === RoomTypeEnum.PUBLIC)
          home.rooms = rooms.filter(r => r.room_type === RoomTypeEnum.COMMON).sort(util.sortByName())
          home.shouldShowHideBtn = home.rooms.length > 16
        })
        this.homes = homeIds.map(id => homeMap[id])
      } catch (err) {
        console.log(err)
      } finally {
        this.spinShow = false
      }
    },
    showSidebar (home, room) {
      this.highlightRoomId = room.id
      // this.span = 18;
      if (!home || !room) {
        return
      }

      if (this.sidebarVisible && this.selectedRoom && this.selectedRoom.id === room.id) {
        this.sidebarVisible = false
        return
      }

      this.sidebarVisible = true
      this.selectedHome = home

      http.request(this, api.room_info, [room.id], null, (res, err) => {
        if (err || !res) {
          return
        }
        this.selectedRoom = res
      })
    },

    openRoom (room) {
      this.hideSidebar()
      const home = this.selectedHome
      const roomId = room.id
      this.$store.dispatch('addTab', home).then(() => {
        this.$router.push({
          path: `/tenancy-device/${home.id}`,
          query: {
            roomId
          }
        })
      })
    },

    refreshHomeList () {
      this.loadData()
      this.hideSidebar()
    },

    hideSidebar () {
      this.sidebarVisible = false
    },

    search (params) {
      params.limit = LIMIT
      this.params = params
      this.currPage = 1
      this.loadData()
    },

    // 过滤房源类型
    filterHomeType (homeTypes) {
      this.params.home_type = homeTypes || null
      this.params.offset = 0
      this.currPage = 1
      this.loadData()
    },

    filterStore (stores) {
      this.params.branch_id = stores
      this.params.offset = 0
      this.currPage = 1
      this.loadData()
    },

    getHomeType (type) {
      let item = HomeTypeEnum.properties[type]
      if (item) {
        return item.text
      }
      return '未知'
    },

    onPageChange (page) {
      this.params.offset = (page - 1) * LIMIT
      this.loadData()
    },

    toHomeDetail (tabsName) {
      this.hideSidebar()
      this.$router.push(`/tenancy-device${tabsName}`)
    },

    openHomeDetail (home) {
      this.hideSidebar()
      this.$store.dispatch('addTab', home).then(() => {
        this.$router.push(`/tenancy-device/${home.id}`)
      })
    },

    removeTab (id) {
      this.$store.dispatch('removeTab', id).then(path => {
        this.$router.push('/tenancy-device' + path)
      })
    }
  },
  beforeRouteLeave (to, from, next) {
    this.$store.dispatch('cleanHomeStateCache').then(() => {
      next()
    })
  }
}
</script>

<style lang="less">
@baseGreen: #05bac5;
@fontGreen: #09868e;
@iconGreen: #5ec5c8;

@borderRed: #d98277;
@fontRed: #c50505;
@iconRed: #e27777;

@fontGrey: #5b5b5b;
@iconGrey: #a8a8a8;

.no-break{
    white-space: nowrap;
}

.c-home-rooms{
    display: flex;
    padding: 15px;

    &__tenant{
        position: absolute;
        right: 5px;
        top: 5px;
    }

    &__public{
        position: relative;
        display: flex;
        cursor: pointer;
        width: 100px;
        margin-right: 10px;
        justify-content: stretch;
        border-radius: 4px;
        background-color: #f8f8f9;
    }

    &__public, &__item{
        &.is-working{
            background: #cdf1f3;
        }
        &.is-error{
            background: #f0c3bd;

            & .c-home-rooms__tenant{
                color: @fontGreen;
            }
        }
    }

    &__main{
        display: flex;
        flex: 1;
        margin-bottom: -10px;
    }

    &__floor{
        display: flex;
        margin: 0 -5px;
        margin-top: -5px;
    }

    &__list{
        display: flex;
        flex-wrap: wrap;
        flex: 1;
    }

    &__list--split{
        margin-top: -5px;
    }

    &__item__wrap{
        width: 12.5%;
        padding: 5px;
        justify-content: stretch;
    }

    &__item{
        position: relative;
        cursor: pointer;
        width: 100%;
        height: 100%;
        min-height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        // line-height: 50px;
        padding: 0 10px;
        margin-bottom: 10px;
        border-radius: 4px;
        background-color: #f8f8f9;
        font-size: 12px;
        // text-overflow: ellipsis;
        // white-space: nowrap;
        &__name{
            position: relative;
            display: flex;
            justify-content: center;
            // max-height: 40px;
            line-height: 18px;
            overflow: hidden;
            word-break: break-all;

            &.is-clamp{
                font-size: 12px;
            }

            &.is-clamp:after {
                content: "";
                position: absolute;
                bottom: 0;
                right: 0;
                width: 40px;
                height: 20px;
                background: linear-gradient(to right, transparent, #f8f8f9);
            }
        }

        &:hover{
            background-color: darken(#f8f8f9, 5%);
            .c-home-rooms__item__name.is-clamp:after{
                background: linear-gradient(to right, transparent, darken(#f8f8f9, 5%));
            }
        }
    }
}

.c-home-list{
    position: relative;
    margin-bottom: 20px;
    border: 1px solid #e9eaec;

    &__title{
        display: flex;
        align-items: center;
        height: 47px;
        padding-right: 20px;
        padding-left: 15px;
        background-color: #f5f5f5;
        border-left: 5px solid @baseGreen;

        &__main{
            position: relative;
            width: 70px;
            font-size: 16px;
            font-weight: 600;
            padding-right: 20px;
            overflow: hidden;
            &::after{
                content: '|';
                position: absolute;
                right: 10px;
                top: 50%;
                font-weight: 400;
                transform: translateY(-50%);
            }
        }

        &__content{
            flex: 1;
            overflow: hidden;
            padding-right: 10px;
        }

        &__split{
            margin: 0 10px;
        }

        &__btn{
            width: 76px;
            height: 30px;
            padding: 0;
            margin-left: auto;
            font-weight: bold;
        }
    }
}

.no-data {
    background: #eee;
    padding: 50px 0;
    text-align: center;
}

/* ----- color ----- */
.color-wrap {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 22px 0 8px 0;
}
.color-wrap span {
    display: inline-block;
    margin: 0 8px 0 30px;
    width: 14px;
    height: 14px;
    box-sizing: border-box;
    border: 1px solid #bbbec4;
    font-size: 14px;
}
.color-wrap span:first-child {
    margin: 0 8px 0 5px;
}
.color-wrap .color1 {
    background: #f8f8f9;
}
.color-wrap .color2 {
    background: @baseGreen;
}
.color-wrap .color3 {
    background: #df4242;
}

/* ----- home ----- */

.home-list-padding {
    padding: 0 5px 0 0;
}
.home-item {
    margin-bottom: 15px;
    border: 1px solid #e9eaec;
    position: relative;
}
.home-info {
    font-size: 12px;
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    background: #efeff1;
    justify-content: space-between;
    padding: 10px 20px 7px 5px;
    border-left: 5px solid @baseGreen;
}
.home-info span {
    padding: 0 10px;
}
.home-a {
    flex: 1;
    text-align: right;
}
.home-icon-open {
    position: absolute;
    top: 74px;
    right: 20px;
    cursor: pointer;
    color: @baseGreen;
    transition: transform 0.3s;
    &.is-open {
        transform: rotate(180deg);
    }
}

/* ----- room ----- */
.room-public-wrap {
    position: relative;
    display: flex;
    margin: 0 0px 14px 0;
    min-width: 123px;
    border-radius: 4px;
}

.room-public {
    width: 100%;
    min-height: 50px;
    box-sizing: border-box;
}
.room-item {
    display: inline-block;
    // border: none;
    border-radius: 4px;
    box-sizing: border-box;
    border: 1px solid transparent;
    cursor: pointer;

    &.highlightRoomItem {
        border: 1px solid @baseGreen;
    }
}
.room-common {
    position: relative;
    min-width: 67px;
    width: 10%;
    margin: 0 1% 14px 0;
    height: 50px;
    box-sizing: border-box;
}
.decentralized-wrap {
    .room-common {
        margin: 0 0 14px 1%;
    }
}
.room-item.has-device-normal {
    background: #cdf1f3;
    color: @fontGreen;

    .icon-tenant {
        color: @iconGreen;
    }
}

.room-item.has-device-normal:hover {
    background: #b3e7ea;
}

.room-item.has-device-exception {
    background: #f3d1cd;
    color: @fontRed;

    .highlightRoomItem {
        border: 1px solid @borderRed;
    }
    .icon-tenant {
        color: @iconRed;
    }
}

.room-item.has-device-exception:hover {
    background: #f0c3bd;
}

.room-item:hover {
    background: #e7e7e7;
}

.room-item a {
    display: block;
    text-align: center;
    color: @fontGrey;
    border-radius: 2px;
}

.room-item-poptip {
    width: 100%;
    height: 100%;
}

.ivu-poptip-rel {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;

    a {
        flex: 1;
    }
    .room-more {
        cursor: pointer;
        padding-right: 10px;
        color: @iconGrey;
    }
}

.rooms-children-wrap {
    .room-common {
        width: 100px;
    }
}

.icon-tenant {
    position: absolute;
    top: 4px;
    right: 5px;
    font-size: 16px;
    color: @iconGrey;
}

/* ----- decentralized ----- */
.decentralized-wrap {
    display: flex;
    flex-flow: row nowrap;
    padding: 15px 15px 0 15px;
    .room-public-wrap {
        padding-bottom: 0;
    }
}

/* ----- centralized ----- */
.centralized-wrap {
    display: flex;
    padding: 15px 15px 0 15px;
}
.floor {
    width: 9%;
    height: 50px;
    margin: 0 12px;
    background: #f8f8f9;
    border-radius: 4px;
    line-height: 50px;
    text-align: center;
    font-weight: bold;
}

.floors-wrap {
    width: 100%;
}
.floor-wrap {
    display: flex;
    align-items: flex-start;
    .rooms-wrap {
        flex: 1;
    }
}
.room-item {
    background-color: #f8f8f9;
    display: flex;
    align-items: center;
    justify-content: center;
}
.rooms-wrap {
    width: 100%;
    display: flex;
    flex-flow: row wrap;
    padding-right: 90px;
}

.rooms-children-wrap {
    padding: 10px;
    width: 266px;
    .room-item {
        margin: 10px;
    }
}

/* ----- sidebar ----- */
.sidebar-ani {
    transition: right 0.3s;
    -moz-transition: right 0.3s; /* Firefox 4 */
    -webkit-transition: right 0.3s; /* Safari and Chrome */
    -o-transition: right 0.3s; /* Opera */
}
.sidebar-ani2 {
    transition: min-width 0.3s;
    -moz-transition: min-width 0.3s; /* Firefox 4 */
    -webkit-transition: min-width 0.3s; /* Safari and Chrome */
    -o-transition: min-width 0.3s; /* Opera */
}
</style>
